<template>
  <yt-page title="设备列表">
    <yt-cell-cascader desc="选择区域" class="fixed-top" v-model="select" :list="tree" label="name" val="id" changeOnSelect showLast></yt-cell-cascader>
    <yt-group ref="group" :searchApi="searchApi" :group="false">
      <yt-card slot-scope="item" :title="item.DeviceName" :edge="false">
        <yt-cell label="设备类型" :value="item.DeviceCategory"></yt-cell>
        <yt-cell label="报警上限" :value="item.AlarmUpperThreshold"></yt-cell>
        <yt-cell label="报警下限" :value="item.AlarmLowerThreshold"></yt-cell>
        <yt-cell label="实时值" :value="item.value"></yt-cell>
        <yt-cell label="管理部门" :value="item.AdminDepartment"></yt-cell>
        <yt-cell label="管理人员" :value="item.AdminPersonnel" border="none"></yt-cell>
      </yt-card>
    </yt-group>
  </yt-page>
</template>

<script>
import { JudgeRole, Store, GetStore } from '@/store'
import { commonApi } from '@/common/api/commonApi.js'
import { ReplaceDictionary, BuildTree, findNodeFromTree, findChildrenFromTree } from '@/common/utils'

export default {
  data() {
    return {
      tree: [],
      list: [],
      currentGrid: {},
      currentGridIds: [],
      select: [],
      searchApi: async ({ skip, limit }) => {
        let containedIn = {}
        if (this.currentGridIds.length) {
          containedIn = { gridId: this.currentGridIds }
        }
        let items = await commonApi.search('measure_automation', {
          containedIn: containedIn,
          skip,
          limit
        })
        let dic = await commonApi.dictionary('equipment_category')
        return ReplaceDictionary(items, { DeviceCategory: dic })
      }
    }
  },
  watch: {
    select(ids) {
      let nodes = findNodeFromTree(this.tree, [ids[ids.length - 1]])
      this.onRefresh(nodes[0])
    }
  },
  activated() {
    if (!this.$router.$isBack) {
      this.select = []
      this.currentGridIds = []
      this.fetchGridTree()
    }
  },
  methods: {
    async fetchGridTree() {
      let grids = await commonApi.search('sys_grid', { limit: 1000 })
      let tree = BuildTree(grids, '', 'parentId')
      JudgeRole()
        .enterprise(() => {
          let id = GetStore(Store.enterprise).id
          let grid = grids.find(
            v => v.belongedEnterprise && v.belongedEnterprise.id === id
          )
          this.tree = findNodeFromTree(tree, [grid.id])
        })
        .fail(() => {
          this.tree = tree
        })
    },
    async onRefresh(node) {
      this.currentGrid = node
      let children = findChildrenFromTree(node)
      this.currentGridIds = children.map(v => v.id)
      this.list = []
      setTimeout(() => {
        this.$refs.group.startPull()
      }, 500)
    }
  }
}
</script>

<style lang="stylus" scoped>
>>>.yt-pull-scroll {
  padding-bottom: 50px;
}

>>>.yt-cellCascader {
  position: relative;
  z-index: 1;
}
</style>
